package cn.bugstack.springframework.test;

public class VolatileDemo {
    //开关
    private static volatile boolean onCtrl;

    //打开开关
    public void turnOn() {
        onCtrl = true;
    }

    //执行业务方法
    public void doWork() {
        System.out.println("doing work now.");
    }

    //主线程
    public static void main(String[] args) {

        VolatileDemo demo = new VolatileDemo();

        //开了一个线程
        Thread workThread = new Thread(new Runnable() {
            @Override
            public void run() {
                //无限等待开关打开
                while (!onCtrl) {
                }
                demo.doWork();
            }
        });

        //线程启动
        workThread.start();

        try {
            //主线程停止2秒
            Thread.sleep(2000);
            //主线程修改的变量值对其他线程不可见

            System.out.println("onCtrl is on.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
